from django import forms
from web import models
from django.core.exceptions import ValidationError

class BaseForm(object):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, item in self.fields.items():
            item.widget.attrs['class'] = 'form-control'
            item.widget.attrs['placeholder'] = f'请输入{item.label}'


class ProjectForm(BaseForm, forms.ModelForm):
    desc = forms.CharField(widget=forms.Textarea(), label='项目描述')
    color=forms.IntegerField()
    name = forms.CharField(label='项目名称')
    class Meta:
        model = models.Project
        fields = ['name', 'desc','color']

    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request=request

    def clean_name(self):
        '''
        项目名校验
        :return:
        '''
        #检查项目名称是否重复
        name=self.cleaned_data['name']
        exists=models.Project.objects.filter(name=name,creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError('此项目名已存在')
        #检查项目个数是否超出本身的价格策略
        permission_project_count=self.request.tracer.price_policy.project_num
        count=models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count>=permission_project_count:
            raise ValidationError('项目个数已经满了，请升级套餐')
        return name